#!/bin/bash
: <<COMMENT
  Copyright (C) 2012 Tri Le <trile7 at gmail dot com>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation version 3.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
COMMENT

$fm_import
if [[ -z $fm_pwd ]]; then
  echo "This script is intended to be run with spacefm only."
  exit 1
fi
mkdir -p "$fm_cmd_data"
trashrc=$fm_cmd_data/trashrc
trashcan=$HOME/.local/share/Trash
if [[ ! -f "$trashrc" ]]; then
  echo "#Maximum file size that can be moved to trash in byte.  Leave blank to ignore file size" >> "$trashrc"
  echo maxsize=1000000000 >> "$trashrc"
fi
source "$trashrc"
mkdir -p "$trashcan/files" "$trashcan/info"
if [[ $? -ne 0 ]]; then
  echo "Cannot create trashcan"
  echo "Please make sure you can write to $HOME/.local/share directory"
  exit 1
fi
if echo $fm_pwd | egrep -q ^$trashcan; then
  echo "Cannot trash files in trashcan"
  exit
fi
if [[ -z $fm_file ]]; then
  echo "This script moves selected item to $trashcan"
  spacefm "$fm_cmd_data"
  exit
fi
for i in "${fm_files[@]}"; do
  if [[ $maxsize ]] && [[ `du -bs "$i" | awk '{print $1}'` -gt $maxsize ]]; then
    echo "Skip $i because it's larger than $maxsize"
    continue
  fi
  filename=`basename "$i"`
  while [[ -e "$trashcan/files/$filename" ]]; do
    (( j++ ))
    filename=`basename "$i"`_$j
    if [[ $j -gt 99 ]]; then
      echo "Cannot trash $i due to conflict in $trashcan"
      continue 2
    fi
  done
  mv "$i" "$trashcan/files/$filename" && echo -e "[$filename trash info]\nPath=$i\nDeletionDate=`date`" > "$trashcan/info/$filename.trashinfo"
done
exit $?
